package com.unieagle.exam.ui;

import java.util.List;

import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.unieagle.exam.R;
import com.unieagle.exam.account.AccountManager;
import com.unieagle.exam.http.IVolleyListener;
import com.unieagle.exam.http.ResultTipHelper;
import com.unieagle.exam.http.TaskHelper;
import com.unieagle.exam.http.VolleyRequest;
import com.unieagle.exam.http.VolleyTask;
import com.unieagle.exam.model.UserInfoResult;
import com.unieagle.exam.model.VerificationCodeResult;
import com.unieagle.exam.utils.PhoneCheckUtils;
import com.unieagle.exam.utils.SharedPreferenceUtils;

public class LoginActivity extends BaseActivity  implements View.OnClickListener ,IVolleyListener{

    private long firstTime = 0;
    
    private Button mBtAlreadyRegister;
    private Button mBtSubmitLogin;
    private Button mBtGetCode;

    private EditText mEtPhone;
    private TextView mTtPhone;
    private EditText mEtCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersedStyle();

        setContentView(R.layout.login_activity_layout);

        mBtAlreadyRegister = (Button) findViewById(R.id.already_register);
        mBtAlreadyRegister.setOnClickListener(this);

        mBtSubmitLogin = (Button) findViewById(R.id.login_submit);
        mBtSubmitLogin.setOnClickListener(this);

        mBtGetCode = (Button)findViewById(R.id.get_code);
        mBtGetCode.setOnClickListener(this);

        mEtPhone = (EditText) findViewById(R.id.phone);
        mEtCode = (EditText) findViewById(R.id.code);
        mTtPhone = (TextView) findViewById(R.id.phone_tip);

        mEtPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b){
                    mTtPhone.setVisibility(View.GONE);
                    mEtPhone.setActivated(false);
                }else{
                    checkPhoneInput();
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.already_register:
                startActivity(new Intent(this,RegisterActivity.class));
                finish();
                break;
            case R.id.get_code:
                if(checkPhoneInput()){
                    VolleyTask task = TaskHelper.createVerificationCodeTask(mEtPhone.getText().toString());
                    task.setVolleyListener(this);
                    VolleyRequest.getInstance().request(task);
                    showProgress("获取中");
                }
                break;
            case R.id.login_submit:
                if(!checkPhoneInput()){
                    return;
                }
                if(TextUtils.isEmpty(mEtCode.getText().toString())){
                    Toast.makeText(this,"验证码不能为空", Toast.LENGTH_SHORT).show();
                    mEtCode.setActivated(true);
                    return;
                }
                mEtCode.setActivated(false);
                VolleyTask signinTask = TaskHelper.createSigninTask(mEtPhone.getText().toString(), 
                		mEtCode.getText().toString(), SharedPreferenceUtils.getPushToken(this));
                signinTask.setVolleyListener(this);
                VolleyRequest.getInstance().request(signinTask);
                showProgress("登录中");
                break;
        }
    }


    @Override
    public void onComplete(VolleyTask task, Object result) {
        if(result != null){
            if(result instanceof VerificationCodeResult){
            	String tip = ResultTipHelper.parseResult(result,VerificationCodeResult.class);
            	if(TextUtils.isEmpty(tip)) {
            		Toast.makeText(this, "验证码已发送", Toast.LENGTH_SHORT).show();
                    mEtCode.setText(((VerificationCodeResult) result).getVerification_code());
            	}else {
            		Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
            	}
            }else if(result instanceof UserInfoResult){
            	AccountManager.getInstance().updateUserInfoResult((UserInfoResult)result);
            	if(!AccountManager.getInstance().getUserInfo().getActivation_status().equals("activation_active")) {
            		SharedPreferenceUtils.setFreeExamCount(this, AccountManager.getInstance()
            				.getUserInfo().getTrail_count());
            		Intent i = new Intent(LoginActivity.this, SubjectChooseActivity.class);
            		startActivity(i);
            		finish();
            	} else {
            		List<Integer> subjects = AccountManager.getInstance().getUserInfo().getSelected_subjects();
            		if(subjects == null || subjects.size() == 0) {
            			showMessage();
            		} else {
            			Intent i = new Intent(LoginActivity.this, AddSubjectActivity.class);
            			i.putExtra("from_splash", true);
            			startActivity(i);
            			finish();
            		}
            	}
            }
        }
        dismissProgress();
    }

    @Override
    public void onError(VolleyTask task, VolleyError volleyError) {
        if(task.getResponseType() == VerificationCodeResult.class ){
            Toast.makeText(LoginActivity.this,"获取验证码失败",Toast.LENGTH_SHORT).show();
        }else if(task.getResponseType() == UserInfoResult.class){
            Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
        }
        dismissProgress();
    }

    private boolean checkPhoneInput(){
        if(mEtPhone.getText().length() == 0){
            mTtPhone.setText("不能为空");
            mTtPhone.setVisibility(View.VISIBLE);
            mEtPhone.setActivated(true);
            return false;
        }else if(!PhoneCheckUtils.isMobileNO(mEtPhone.getText().toString())){
            mTtPhone.setText("格式错误");
            mTtPhone.setVisibility(View.VISIBLE);
            mEtPhone.setActivated(true);
            return false;
        }
        mTtPhone.setVisibility(View.GONE);
        mEtPhone.setActivated(false);
        return true;
    }

    public static class MessageDialog extends DialogFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setStyle(DialogFragment.STYLE_NO_TITLE, R.style.normal_transparent_dialog);
            setCancelable(true);
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Dialog dialog= super.onCreateDialog(savedInstanceState);
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(false);
            return dialog;
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.login_success_dialog_layout, container, true);
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            View v = view.findViewById(R.id.close);
            if(v != null){
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    	dismiss();
                    	Intent i = new Intent(getActivity(), AddSubjectActivity.class);
            			i.putExtra("from_splash", true);
            			startActivity(i);
                        getActivity().finish();
                    }
                });
            }
        }
    }

    public void showMessage(){
        MessageDialog dialog = new MessageDialog();
        dialog.show(getFragmentManager(),"登录成功");
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000)
                {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                }
                else
                {
                    finish();
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
    
}
